#ifndef _EXTERNALSORT_H_
#define _EXTERNALSORT_H_

#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

// sort size 64 bit unsigned int values from fdInput using memSize bytes of main memory
// and store the result in the fdOutput file
void externalSort(int fdInput, unsigned long size, int fdOuput, unsigned long memSize);

// write the uint64_t elements of the vector to fdOut after sorting them
// does not close file handle
void writeSortedToFile(std::vector<uint64_t> elements, int fdOut);

// writes the minimum element of values to fdOutput, and replaces that element with the next
// element from the according inputs file, if any remains
int writeMinimumToFileAndUpdate(uint64_t values[], int indices[], int fdResult, FILE *inputs[], long elementCount[]);

// returns the index of the minimum value in the array for which the corresponding index in indices
// is lower than the entry at elementCount. size denotes the number of elements in the array.
// if no such value can be found, -1 is returned
int minIndex(uint64_t values[], int size, int indices[], long elementCount[]);

// tries to read from pFile the n-th uint64_t (=n*sizeof(uint64_t) starting from SEEK_SET)
uint64_t readOffsetFromFile(FILE *pFile, int n);
#endif // _EXTERNALSORT_H_
